package cn.enilu.flash.service.blindbox;

import cn.enilu.flash.bean.entity.blindbox.BlindBoxGoodsUser;
import cn.enilu.flash.bean.entity.blindbox.UserFunds;
import cn.enilu.flash.bean.entity.shop.Goods;
import cn.enilu.flash.bean.vo.blindbox.BlindBoxGoodsUserVO;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.convert.GiftConvert;
import cn.enilu.flash.dao.blindbox.BlindBoxGoodsUserRepository;
import cn.enilu.flash.dao.blindbox.UserFundsRepository;
import cn.enilu.flash.dao.shop.GoodsRepository;
import cn.enilu.flash.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author HYF
 * @ClassName BlindboxService
 * @date 2022年04月27日 5:08 下午
 */
@Service
public class BlindboxGoodsUserService extends BaseService<BlindBoxGoodsUser, Long, BlindBoxGoodsUserRepository> {

    @Autowired
    private GoodsRepository goodsRepository;

    @Resource
    private BlindBoxGoodsUserRepository blindBoxGoodsUserRepository;


    public List<BlindBoxGoodsUserVO> queryBlindBoxGoodsUserList(Long idUser) {
        List<BlindBoxGoodsUser> blindBoxGoodsUsers = queryAll(SearchFilter.build("userId", idUser));
        List<BlindBoxGoodsUserVO> goodsUserVOS = GiftConvert.INSTANCE.convertGoodsUserList(blindBoxGoodsUsers);
        for (BlindBoxGoodsUserVO goodsUserVO : goodsUserVOS) {
            Optional<Goods> goods = goodsRepository.findById(goodsUserVO.getGoodsId());
            goodsUserVO.setGoods(goods.get());
        }
        return goodsUserVOS;
    }

    /**
     * 回收商品
     *
     * @param ids
     * @param idUser
     */
    @Transactional(rollbackFor = Exception.class)
    public  Long recoveryGoods(List<Long> ids, Long idUser) {
//        goodsRepository.
        List<BlindBoxGoodsUser> blindBoxGoodsUsers = blindBoxGoodsUserRepository.findAllById(ids);
        blindBoxGoodsUsers = blindBoxGoodsUsers.stream().filter(blindBoxGoodsUser -> blindBoxGoodsUser.getUserId().equals(idUser)).collect(Collectors.toList());
        if (blindBoxGoodsUsers.size() != ids.size()) {
            throw new RuntimeException("异常订单");
        }
        delete(ids);

        List<Long> goodsIds = blindBoxGoodsUsers.stream().map(BlindBoxGoodsUser::getGoodsId).collect(Collectors.toList());
        List<Goods> goodsList = goodsRepository.findAllById(goodsIds);
        Long price = 0L;
        for (Goods goods : goodsList) {
            price += goods.getPrice().longValue();
        }
        return price;
    }
}